package com.yuyang.wifi.activitys.mine;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mobads.sdk.api.CPUWebAdRequestParam;
import com.baidu.mobads.sdk.api.CpuAdView;
import com.baidu.mobads.sdk.api.CpuLpFontSize;
import com.yuyang.wifi.R;
import com.yuyang.wifi.base.BaseActivity;
import com.yuyang.wifi.base.BaseResult;
import com.yuyang.wifi.constant.AppConstant;
import com.yuyang.wifi.constant.ConstantsMsg;
import com.yuyang.wifi.model.AdTypeInfoModel;
import com.yuyang.wifi.model.AdTypeInfoResult;
import com.yuyang.wifi.utils.DeviceUtil;
import com.yuyang.wifi.utils.RxUtil;
import com.yuyang.wifi.utils.SpUtil;
import com.yuyang.wifi.utils.ToastUtils;
import com.yuyang.wifi.utils.network.BaseDataSubscriber;
import com.yuyang.wifi.utils.network.HttpErrorHandler;
import com.yuyang.wifi.utils.network.HttpManager;
import com.yuyang.wifi.utils.network.RxDataInstance;
import com.yuyang.wifi.views.LoadCsjMsgUtils;
import com.yuyang.wifi.views.LoadCsjNewInsertFullAdUtils;
import com.yuyang.wifi.views.LoadYLHJiliVideoUtils;
import com.yuyang.wifi.views.LoadYlhMBMsgAdUtils;
import com.yuyang.wifi.views.NormalWhiteTopBar;
import com.yuyang.wifi.views.XTextView;

import java.util.Random;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class NetworkTestSpeedActivity extends BaseActivity {

    @BindView(R.id.tool_bar)
    NormalWhiteTopBar toolBar;
    @BindView(R.id.express_container)
    FrameLayout mExpressContainer;
    @BindView(R.id.rl_bd_contain_layout)
    RelativeLayout rlBdContainLayout;
    @BindView(R.id.network_delay_time)
    XTextView networkDelayTime;
    @BindView(R.id.xt_download_speed)
    XTextView xtDownloadSpeed;
    @BindView(R.id.xt_upload_speedd)
    XTextView xtUploadSpeed;

    private CpuLpFontSize mDefaultCpuLpFontSize = CpuLpFontSize.REGULAR;
    private boolean isDarkMode = false;
    private CpuAdView mCpuView;
    public static final String TAG = "CpuAdActivity";
    private int type;
    private LoadCsjMsgUtils csjMsgInstance;
    private int screenWidth;
    private LoadYlhMBMsgAdUtils loadYlhMBMsgAdUtils;

    @Override
    protected void initActionBar() {
        toolBar.setActionBarCentreTitle("网络测速");
        toolBar.setsetActionBarBottomLine(false);
        toolBar.setsetActionBarLeftIcon(R.mipmap.toolbar_left_arrow_back_icon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_network_test_speed;
    }

    @Override
    protected void initContentView() {

        screenWidth = DeviceUtil.getWidth(NetworkTestSpeedActivity.this);
        csjMsgInstance = LoadCsjMsgUtils.getInstance();
        csjMsgInstance.setLoadFailureListener(new LoadCsjMsgUtils.OnLoadFailureListener() {
            @Override
            public void onLoadFailureListener() {
                playErrorRepalceAd(2);
            }
        });

        loadYlhMBMsgAdUtils = LoadYlhMBMsgAdUtils.getInstance();
        loadYlhMBMsgAdUtils.setLoadFailureListener(new LoadYlhMBMsgAdUtils.OnLoadFailureListener() {
            @Override
            public void onLoadFailureListener() {
                Log.i(TAG, "onNoAD: " + "2222");
                playErrorRepalceAd(1);
            }
        });
        loadYlhMBMsgAdUtils.load(NetworkTestSpeedActivity.this, mExpressContainer, "ylh_msg_network_test_finish");

        Random random = new Random();
        int num = random.nextInt(10) + 15;
        int num2 = random.nextInt(10) + 35;
        int num3 = random.nextInt(10) + 25;
        networkDelayTime.setText("sBig" + num + ".6eBigms");
        xtDownloadSpeed.setText("sBig" + num2 + ".3eBigms");
        xtUploadSpeed.setText("sBig" + num3 + ".8eBigms");

        getAdTypeInfo();
        showSelectedCpuWebPage();
    }


    /**
     * 内容联盟模板渲染，展示频道
     */
    private void showSelectedCpuWebPage() {

        /**
         *  注意构建参数时，setCustomUserId 为必选项，
         *  传入的outerId是为了更好的保证能够获取到广告和内容
         *  outerId的格式要求： 包含数字与字母的16位 任意字符串
         */

        /**
         *  推荐的outerId获取方式：
         */
        String outerId = SpUtil.find(AppConstant.KEY_OUTERID);
        if (TextUtils.isEmpty(outerId)) {
            outerId = UUID.randomUUID().toString()
                    .replace("-", "")
                    .substring(0, 16);
            SpUtil.saveOrUpdate(AppConstant.KEY_OUTERID, outerId);
        }

        CPUWebAdRequestParam cpuWebAdRequestParam = new CPUWebAdRequestParam.Builder()
                .setLpFontSize(mDefaultCpuLpFontSize)
                .setLpDarkMode(isDarkMode)
                .setCityIfLocalChannel("北京")
                .setCustomUserId(outerId)
                .build();

        mCpuView = new CpuAdView(this, ConstantsMsg.KS_BAIDU_APP_SID, ConstantsMsg.KS_BAIDU_AD_TYPE, cpuWebAdRequestParam,
                new CpuAdView.CpuAdViewInternalStatusListener() {
                    @Override
                    public void loadDataError(String message) {
                        Log.d(TAG, "loadDataError: " + message);
                    }

                    @Override
                    public void onAdClick() {
                        Log.d(TAG, "onAdClick: ");
                    }

                    @Override
                    public void onAdImpression(String impressionAdNums) {
                        Log.d(TAG, "onAdImpression: impressionAdNums " + impressionAdNums);
                    }

                    @Override
                    public void onContentClick() {
                        Log.d(TAG, "onContentClick: ");
                    }

                    @Override
                    public void onContentImpression(String impressionContentNums) {
                        Log.d(TAG, "onContentImpression: impressionContentNums = " +
                                impressionContentNums);
                    }
                });

        // 考虑到媒体在 锁屏开关等场景下 有刷新页面的需求，SDK目前将控件的创建与
        // 数据的请求进行拆分，媒体在已创建控件的前提下，可以直接调用下面这行代码来请求或着更新数据
        mCpuView.requestData();
        RelativeLayout.LayoutParams reLayoutParams = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        reLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        rlBdContainLayout.addView(mCpuView, reLayoutParams);
    }


    @Override
    public void onResume() {
        super.onResume();
        if (mCpuView != null) {
            mCpuView.onResume();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mCpuView != null) {
            mCpuView.onPause();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mCpuView != null) {
            mCpuView.onDestroy();
        }
    }

    private void getAdTypeInfo() {
        RxDataInstance.getInstance().initMap(NetworkTestSpeedActivity.this)
                .put("entryNumber", "5");
        HttpManager.getInstance().getApi().getAdTypeInfo(RxDataInstance.getInstance().getParamMap())
                .compose(RxUtil.<AdTypeInfoResult>bindLifecycleAndApplySchedulers(this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseDataSubscriber<AdTypeInfoResult>(new HttpErrorHandler() {
                    @Override
                    public void onHttpError(BaseResult result) {
                        ToastUtils.showShortToast(NetworkTestSpeedActivity.this, result.getErrorMessage());
                    }

                    @Override
                    public void onHttpException(Throwable e) {
                        // dismissLoadingDialog();
                    }
                }) {
                    @Override
                    public void onDataNext(AdTypeInfoResult result) {
                        int resultCode = result.getResultCode();
                        if (0 == resultCode) {
                            AdTypeInfoModel data = result.getData();
                            if (null != data) {
                                type = data.getType();
                                if (type == 1) {
                                    csjMsgInstance.load(NetworkTestSpeedActivity.this, mExpressContainer, screenWidth, 287, "csj_msg_network_test_finish");
                                } else if (type == 2) {
                                    loadYlhMBMsgAdUtils.showInterActionAdVideo();
                                }
                            }
                        } else {
                            ToastUtils.showShortToast(NetworkTestSpeedActivity.this, result.getErrorMessage());
                        }
                    }
                });
    }

    private void playErrorRepalceAd(int type) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (type == 1) {
                    Log.i(TAG, "onNoAD: " + "3333");
                    csjMsgInstance.load(NetworkTestSpeedActivity.this, mExpressContainer, screenWidth, 287, "csj_msg_network_test_finish");
                } else {
                    loadYlhMBMsgAdUtils.showInterActionAdVideo();
                }
            }
        }, 1000);
    }


}
